<script setup>
import { ref,reactive,computed,watch,watchEffect ,onMounted} from "vue";
import {login,getUserInfo} from "@/api/user"
import {useStore} from "@/pinia/index"
import {useRouter} from "vue-router"

const router=useRouter()
const store=useStore()
const username=ref("")
const password=ref("")
const checked = ref(false);
onMounted(()=>{
	try {
		const str=sessionStorage.getItem("user")
		console.log("str:",str);
		if(str){
			const atobStr=window.atob(str.replace(/\"/g,""))
			console.log("atobStr:",atobStr);
			const user=JSON.parse(decodeURIComponent(escape(atobStr)))
			console.log("user:",user);
			if(user?.username&&user?.password){
				username.value=user.username
				password.value=user.password
				checked.value=true
			}
		}
	} catch (error) {
		console.log("error:",error);
	}
})
function userLogin(){
	if(!username.value&&!password.value){
		return
	}
	login(username.value,password.value).then(res=>{
		if(res.code!==0){
			console.log("错误res:",res);
		}else{
			if(checked.value===true){
				const d=JSON.stringify({username:username.value,password:password.value})
				console.log("d:",d);
				
				const user=JSON.stringify(window.btoa(unescape(encodeURIComponent(d))))
				sessionStorage.setItem("user",user)
			}
			const token=res.data
			store.login(token)
			console.log("token:",token);
			LoginGetUserInfo()
		}
	})
}
function LoginGetUserInfo(){
	getUserInfo().then(info=>{
		console.log("info:",info);
			console.log("info.data:",info.data);
		if(info.code===0){
			const data=info.data
			const userInfo={
				id:data.id,
				username:data.username
			}
			console.log("data:",data);
			console.log("userInfo:",userInfo);
			store.setUserInfo(userInfo)
			router.replace("/")
		}
		else{
			console.log("err:",info);
		}
		
	})
}
</script>


<template>
	<div class="login">
		<h1>聊天登录</h1>
		<a-input v-model:value="username" placeholder="账号"/>
		<a-input-password v-model:value="password"  placeholder="密码" />
		
		<div class="jzmm">
			记住账号密码&nbsp;&nbsp;<a-switch v-model:checked="checked" />
		</div>
		<div class="buttonBox">
			<a-button type="primary" @click="userLogin">登录</a-button>
		<a-button class="regButton" type="dashed" @click="router.push('/reg')">注册</a-button>
		</div>
	</div>

</template>


<style scoped>
.login{
	margin: 0 auto;
	padding: 10px;
	max-width: 20rem;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.login>*{
	margin:10px 0;
}
.buttonBox{
	display: flex;
	flex-direction: row;
	align-items: center;
}
.regButton{
	margin-left: 1rem;
}
.jzmm{	
	display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
	font-size: 12px;
	padding-right: 2rem;
}
</style>